package net.rock.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@Getter
@Setter
@Configuration
@ConfigurationProperties("spring.datasource")
public class DataSourceInitConfig {
    private String driverClassName;
    private String url;
    private String username;
    private String password;
    private Integer maxActive; //最大连接数
    private Integer maxIdle;   //最大空闲连接数
    private Integer initialSize; //初始化连接数量
    private Integer minIdle;   //最大空闲数

    @Bean
    @Primary
    public DataSource initDruidDataSource() {
        try (DruidDataSource dataSource = new DruidDataSource()){
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);

            dataSource.setInitialSize(initialSize);
            dataSource.setMaxActive(maxActive);
            dataSource.setMinIdle(minIdle);
            return dataSource;
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
        return null;
    }
}
